package ebj.common.exception;

import java.lang.Thread.State;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import com.google.common.collect.Lists;
import com.google.gson.Gson;

import ebj.common.utils.Http;

class MyBaseHandler implements UncaughtExceptionHandler {
	private String url = "http://182.254.147.110:9090/req_analysis";

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("My name is>>>" + MyBaseHandler.class.getName());
		StackTraceElement[] elements = e.getStackTrace();
		List<String> errList = Lists.newArrayList();
		for (StackTraceElement element : elements) {
			errList.add(new StringBuilder("Error@Class[")
			.append(element.getClassName())
			.append("], Method[")
			.append(element.getMethodName())
			.append("], Line[")
			.append(element.getLineNumber()).append("]").toString()
					);
		}
		ErrorInfo error = new ErrorInfo();
		error.setThreadId(t.getId());
		error.setThreadName(t.getName());
		error.setMsg(e.getMessage());
		error.setClassName(e.getClass().getName());
		// error.setStackTraceElements(elements);
		error.setStackTraceElements(null);
		error.setDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS Z").format(new Date()));
		error.setErrInfos(errList);
		String json_str = new Gson().toJson(error);
		StringEntity entity = new StringEntity(json_str, ContentType.create(
				"application/json", "UTF-8"));
		try {
			String post_req_result = Http.post(url, entity);
			System.out.println(post_req_result);
		} catch (HttpException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		new Thread(new MyThread()).start();
	}
}